/**
 * @author     Gabor Greif <ggreif@gmail.com>
 * @copyright  2009-2010 Gabor Greif
 * @license    http://www.opensource.org/licenses/mit-license.php  MIT License
 * @version    Release: 0.0
 */

#ifndef micker_CLIST_hpp
#define micker_CLIST_hpp

#include "Command.hpp"

namespace micker {

struct List : Comm<>
{
    List(bool which = false)
    : Comm<>(which
             ? CommandProc(ArgumentsMismatch<1>::proc<void, length>)
             : CommandProc(ArgumentsMismatch<2>::proc<void, index>))
    {}

    static std::string length(const std::string& l)
    {
        unsigned flanks(0);
        bool level(false);
        for (std::string::const_iterator i(l.begin()), e(l.end()); i != e; ++i)
        {
            if (std::isspace(*i))
            {
                if (level)
                {
                    level = false;
                }
            }
            else if (!level)
            {
                level = true;
                ++flanks;
            }
        }

        char buf[26];
        std::sprintf(buf, "%u", flanks);
        return buf;
    }

    static std::string index(const std::string& l, const std::string& i)
    {
        unsigned flanks(0);

        if (1 == std::sscanf(i.c_str(), "%u", &flanks))
        {
            bool level(false);
            std::string::const_iterator s(l.begin());

            for (std::string::const_iterator i(s), e(l.end()); i != e; ++i)
            {
                if (std::isspace(*i))
                {
                    if (level)
                    {
                        if (!flanks--)
                        {
                            return std::string(s, i);
                        }

                        level = false;
                    }
                }
                else if (!level)
                {
                    level = true;
                    if (!flanks)
                    {
                        s = i;
                    }
                }
            }

            if (!flanks)
            {
                return std::string(s, l.end());
            }
        }

        return std::string();
    }
};

} // namespace micker

#endif // micker_CLIST_hpp
